package com.yunc.modules.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSpliter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.base.utils.R;
import com.yunc.modules.sys.entity.SysLoginLog;
import com.yunc.modules.sys.service.ISysLoginLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 登录日志
 *
 * @author congcong tao
 * @create 2018/11/21 下午8:06
 */
@RestController
@RequestMapping("sysLoginLog")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysLoginLogController {

    private final ISysLoginLogService sysLoginLogService;

    @GetMapping("/page")
    public R page(Page<SysLoginLog> page, SysLoginLog sysLoginLog) {
        QueryWrapper<SysLoginLog> ew = new QueryWrapper<>();
        ew.like("login_name", sysLoginLog.getLoginName());
        ew.orderByDesc("login_time");
        sysLoginLogService.page(page, ew);
        return R.ok().put("data", page.getRecords()).put("count", page.getTotal());
    }

    @GetMapping("/info")
    public R getCurrentLogin(@NotEmpty(message = "登录名不能为空") String loginName) {
        // 获取上一次登录信息,当前时间点减去30秒
        SysLoginLog log = sysLoginLogService.getLastLogin(loginName);
        // 根据主键获取上一次信息
        R r = R.ok().put("log", log);
        SysLoginLog lastLog;
        if (log != null) {
            lastLog = sysLoginLogService.getLastById(log.getId());
            r.put("lastLog", lastLog);
        }
        return r;
    }

    @DeleteMapping("/del/{ids}")
    public R info(@PathVariable String ids) {
        List<String> idsList = StrSpliter.splitTrim(ids, ',', true);
        if (CollUtil.isEmpty(idsList)) {
            return R.error("传入值格式错误");
        }
        boolean flag = sysLoginLogService.removeByIds(idsList);
        if (flag) {
            return R.ok("删除成功");
        }
        return R.error("删除失败");
    }

}
